package spring.cloud.feign.client;

import java.util.concurrent.ThreadLocalRandom;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;

@RestController
public class FeignController {
	@Autowired
	private GreetingClient greetingClient;

	@RequestMapping("/get-greeting")
//	@SentinelResource(value = "ERROR_RATIO" ,
//	fallback = "fallback", blockHandler = "handleStringException",
//	exceptionsToIgnore = {
//			IllegalStateException.class })
	public String greeting() {
		String S = greetingClient.greeting();
		return S;
		// model.addAttribute("greeting", greetingClient.greeting());
		// return "greeting-view";
	}

	
	@RequestMapping("/execption-rule")
	@SentinelResource(value = "ERROR_RATIO" ,
	defaultFallback = "defaultFallback", blockHandler = "handleStringException",
	exceptionsToIgnore = {
			IllegalStateException.class })
	public String execptionRule() {
		
		
		
		  if (ThreadLocalRandom.current().nextInt(0, 100) > 55) {
              // biz code raise an exception.
			  if (ThreadLocalRandom.current().nextInt(0, 100) > 55) {
	              // biz code raise an exception. catch by Fallback or defaultFallback
	              throw new RuntimeException("oops"); 
	          }else {
	        	  throw new IllegalStateException("not be catch,throw direct");
	          }
             
          }
		 
		return "no execption and block";
		// model.addAttribute("greeting", greetingClient.greeting());
		// return "greeting-view";
	}

	public String handleStringException(BlockException ex) {
		return ("hello from ExceptionUtil, ex= : " + ex.getClass().getCanonicalName());
	}

	public String fallback(Throwable ex) {
		  
		return "Hello from fallback";
	}

	public String defaultFallback() {
		return "Hello from defaultFallback";
	}

}
